﻿using Sc.Cache;
using Sc.Domain;
using Sc.Persistence;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sc.Service
{
    public class Car_UseCarApplicationService
    {
        /// <summary>
        /// 用车申请数据持久层
        /// </summary>
        private readonly Car_UseCarApplicationDAO dao = new Car_UseCarApplicationDAO();
        /// <summary>
        /// 待办事宜服务层
        /// </summary>
        private Sys_ToDoListService service = new Sys_ToDoListService();
        /// <summary>
        /// 意见数据持久层
        /// </summary>
        private OpinionsDAL oDao = new OpinionsDAL();

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="ent">派车申请</param>
        /// <returns></returns>
        public int SaveData(Car_UseCarApplication ent)
        {
            ent.ApproalUsers = "USER0;";
            ent.NodeCount = 1; ent.InstanceState = 3;
            try
            {
                var bussId = dao.Add(ent);
                Sys.SysWebservice service = CommService.IntanceSys();
                var pid = Convert.ToInt32(ConfigurationManager.AppSettings["gl"]);
                var users = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, ent.OrgzNo);
                foreach (var item in users.Users)
                {
                    MessageParam param = new MessageParam();
                    param.BusinessId = bussId;
                    param.Content = "有新的用车申请需要您进行派车操作！";
                    param.Title = "派车系统通知【" + DateTime.Now + "】";
                    param.Perfix = "UCAC";
                    var mp = ProjectCache.UserToken.Values.Where(it => it.UserId == item.Id).FirstOrDefault();
                    if (mp != null)
                    {
                        CommPushMessage cpm = new CommPushMessage();
                        if (mp.OsType == 0)
                        {
                            param.UserAndroidToken = new List<string>();
                            param.UserAndroidToken.Add(mp.Token);
                            cpm.PushMessageForAndroid(param);
                        }
                        else
                        {
                            param.UserIosToken = new List<string>();
                            param.UserIosToken.Add(mp.Token);
                            cpm.PushMessageForIOS(param);
                        }
                    }
                }
                return bussId;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="ent">派车申请</param>
        /// <returns></returns>
        public int SaveDataForApp(Car_UseCarApplication ent)
        {
            Sys.SysWebservice opa = CommService.IntanceSys();
            var code = "WF001";
            if (ent.IsComplaint)
            {
                code = "WF007";
                dao.UpdateOldData(ent.OldId);
            }
            var wf = opa.GetWF(code, ent.OrgzNo);
            ent.ApproalUsers = wf.AppoalUsers;
            ent.NodeCount = wf.NodeCount;
            try
            {
                var bussId = dao.Add(ent);
                IList<Sys_ToDoList> list = new List<Sys_ToDoList>();
                var firstUs = wf.FirstNodeUsers.Split(',');
                for (int i = 0; i < firstUs.Length; i++)
                {
                    Sys_ToDoList todo = new Sys_ToDoList();
                    RefDataRecord rc = new RefDataRecord(firstUs[i]);
                    todo.UserId = rc.ObjectId;
                    todo.ActionURL = ent.ToDoUrl;
                    todo.CreaterName = ent.UserName;
                    todo.Source = "UCAC" + bussId;
                    todo.UrgencyDegree = 0;
                    todo.Name = ent.StartTime.ToString("yyyy-MM-dd ") + ent.UserName + (code == "WF007" ? "用车申诉" : "用车申请");
                    list.Add(todo);
                }
                service.SaveToDoList(list);
                return bussId;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取用车申请列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <returns></returns>
        public CommModel<Car_UseCarApplication> GetList(int userId, int pageSize, int pageIndex)
        {
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", "AND UserId=" + userId);
            param.Add("A4", "Car_UseCarApplication");
            param.Add("A5", "Id DESC");
            var ht = CommDAO.CommPagination(param);
            DataTable dt = ht["data"] as DataTable;
            List<Car_UseCarApplication> list = new List<Car_UseCarApplication>();
            foreach (DataRow item in dt.Rows)
            {
                list.Add(DataRowToModel(item));
            }
            CommModel<Car_UseCarApplication> ent = new CommModel<Car_UseCarApplication>();
            ent.Data = list;
            ent.PageCount = Convert.ToInt32(ht["PageCount"]);
            ent.RecordCount = Convert.ToInt32(ht["record"]);
            return ent;
        }


        /// <summary>
        /// 获取用车申请列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="pageIndex">当前第几页</param>
        /// <returns></returns>
        public CommModel<Car_UseCarApplication> GetList(int orgz, DateTime start, DateTime end, int pageSize, int pageIndex)
        {
            Hashtable param = new Hashtable();
            param.Add("A1", pageIndex);
            param.Add("A2", pageSize);
            param.Add("A3", "AND StartTime >='" + start.ToString("yyyy-MM-dd HH:mm:ss") + "' And StartTime <= '" + end.ToString("yyyy-MM-dd HH:mm:ss") + "' and OrgzNo = " + orgz);
            param.Add("A4", "Vw_CarUseApp");
            param.Add("A5", "Id DESC");
            var ht = CommDAO.CommPagination(param);
            DataTable dt = ht["data"] as DataTable;
            List<Car_UseCarApplication> list = new List<Car_UseCarApplication>();
            foreach (DataRow item in dt.Rows)
            {
                list.Add(DataRowToModel(item));
            }
            CommModel<Car_UseCarApplication> ent = new CommModel<Car_UseCarApplication>();
            ent.Data = list;
            ent.PageCount = Convert.ToInt32(ht["PageCount"]);
            ent.RecordCount = Convert.ToInt32(ht["record"]);
            return ent;
        }



        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        private Car_UseCarApplication DataRowToModel(DataRow row)
        {
            Car_UseCarApplication model = new Car_UseCarApplication();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());
                }
                if (row["StartAddress"] != null)
                {
                    model.StartAddress = row["StartAddress"].ToString();
                }
                if (row["EndAddress"] != null)
                {
                    model.EndAddress = row["EndAddress"].ToString();
                }
                if (row["StartTime"] != null && row["StartTime"].ToString() != "")
                {
                    model.StartTime = DateTime.Parse(row["StartTime"].ToString());
                }
                if (row["ExDate"] != null && row["ExDate"].ToString() != "")
                {
                    model.ExDate = DateTime.Parse(row["ExDate"].ToString());
                }
                if (row["TotalCount"] != null && row["TotalCount"].ToString() != "")
                {
                    model.TotalCount = int.Parse(row["TotalCount"].ToString());
                }
                if (row["Remark"] != null)
                {
                    model.Remark = row["Remark"].ToString();
                }
                if (row["Reson"] != null)
                {
                    model.Reson = row["Reson"].ToString();
                }
                if (row["InstanceState"] != null && row["InstanceState"].ToString() != "")
                {
                    model.InstanceState = int.Parse(row["InstanceState"].ToString());
                }
                if (row["IsComplaint"] != null && row["IsComplaint"].ToString() != "")
                {
                    if ((row["IsComplaint"].ToString() == "1") || (row["IsComplaint"].ToString().ToLower() == "true"))
                    {
                        model.IsComplaint = true;
                    }
                    else
                    {
                        model.IsComplaint = false;
                    }
                }
                if (row["ComplaintState"] != null && row["ComplaintState"].ToString() != "")
                {
                    model.ComplaintState = int.Parse(row["ComplaintState"].ToString());
                }
                if (row["ApproalUsers"] != null)
                {
                    model.ApproalUsers = row["ApproalUsers"].ToString();
                }
                if (row["NodeCount"] != null && row["NodeCount"].ToString() != "")
                {
                    model.NodeCount = int.Parse(row["NodeCount"].ToString());
                }
                if (row["BussinessState"] != null && row["BussinessState"].ToString() != "")
                {
                    if ((row["BussinessState"].ToString() == "1") || (row["BussinessState"].ToString().ToLower() == "true"))
                    {
                        model.BussinessState = true;
                    }
                    else
                    {
                        model.BussinessState = false;
                    }
                }
                if (row["UserId"] != null && row["UserId"].ToString() != "")
                {
                    model.UserId = int.Parse(row["UserId"].ToString());
                }
                if (row["ZcTonnage"] != null && row["ZcTonnage"].ToString() != "")
                {
                    model.ZcTonnage = Convert.ToDecimal(row["ZcTonnage"].ToString());
                }
                //if (row["CarNo"] != null && row["CarNo"].ToString() != "")
                //{
                //    model.CarNo = row["CarNo"].ToString();
                //}
                //if (row["CarTypeName"] != null && row["CarTypeName"].ToString() != "")
                //{
                //    model.CarTypeName = row["CarTypeName"].ToString();
                //}
                try
                {
                    if (row["Name"] != null && row["Name"].ToString() != "")
                    {
                        model.UserName = row["Name"].ToString();
                    }
                    if (row["DeptName"] != null && row["DeptName"].ToString() != "")
                    {
                        model.Orgz = row["DeptName"].ToString();
                    }
                }
                catch (Exception)
                {
                }
            }
            return model;
        }

        /// <summary>
        /// 获取详情（单个实体）
        /// </summary>
        /// <param name="Id">Id</param>
        /// <returns></returns>
        public Car_UseCarApplication GetDetail(int id)
        {
            var tmp = this.dao.GetDetail(id);
            Sys.SysWebservice sys = CommService.IntanceSys();
            Sys.Users ent = new Sys.Users() { Id = tmp.UserId };
            var mp = sys.GetUser(ent); tmp.Orgz = mp.OrgzName + "//" + mp.DeptName;
            tmp.OpinionList = new OpinionsBLL().GetList("UCAC" + id);
            tmp.DriverScoreList = new DriverScoreDAO().GetList(id, 0);
            return tmp;
        }
        /// <summary>
        /// 审批用车申请
        /// </summary>
        /// <param name="bid">业务ID</param>
        /// <param name="userId">当前用户Id</param>
        /// <param name="opa">操作</param>
        /// <param name="todoId">待办事宜ID</param>
        /// <param name="opContext">审批意见</param>
        /// <returns></returns>
        public ReturnModel Approal(int bid, int userId, int opa, int todoId, string opContext)
        {
            var ent = this.GetDetail(bid);
            if (ent == null) return new ReturnModel() { SourceId = 0, Message = "请上传正确的业务ID" };
            var upUsers = CommService.UpdateApproalUers(ent.ApproalUsers, userId, ent.NodeCount);
            var upNodeCount = CommService.IsUpdateNodeCount(ent.ApproalUsers, userId, ent.NodeCount);
            var list = new List<Sys_ToDoList>();
            if (opa == 1)//拒绝
            {
                ent.InstanceState = 2;
                Sys_ToDoList todo = new Sys_ToDoList();
                todo.ActionURL = string.Empty;
                todo.CreaterName = "系统";
                todo.Name = "您的用车申请已被拒绝";
                todo.Source = "UCAC" + ent.Id;
                todo.State = 0;
                todo.UrgencyDegree = 0;
                todo.UserId = ent.UserId;
                list.Add(todo);
            }
            else
            {
                if (ent.NodeCount == 1)
                {
                    ent.InstanceState = 3;
                    Sys_ToDoList todo = new Sys_ToDoList();
                    todo.ActionURL = string.Empty;
                    todo.CreaterName = "系统";
                    todo.Name = ent.OldId > 0 ? "您的用车申诉已通过" : "您的用车申请已通过";
                    todo.Source = "UCAC" + ent.Id;
                    todo.State = 0;
                    todo.UrgencyDegree = 0;
                    todo.UserId = ent.UserId;
                    list.Add(todo);

                    #region 发送提醒推送至派车人
                    Sys.SysWebservice service = CommService.IntanceSys();
                    var pid = Convert.ToInt32(ConfigurationManager.AppSettings["gl"]);
                    var users = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, ent.OrgzNo);
                    foreach (var item in users.Users)
                    {
                        MessageParam param = new MessageParam();
                        param.BusinessId = bid;
                        param.Content = "有新的用车申请需要您进行派车操作！";
                        param.Title = "派车系统通知【" + DateTime.Now + "】";
                        param.Perfix = "UCAC";
                        var mp = ProjectCache.UserToken.Values.Where(it => it.UserId == item.Id).FirstOrDefault();
                        if (mp != null)
                        {
                            CommPushMessage cpm = new CommPushMessage();
                            if (mp.OsType == 0)
                            {
                                param.UserAndroidToken = new List<string>();
                                param.UserAndroidToken.Add(mp.Token);
                                cpm.PushMessageForAndroid(param);
                            }
                            else
                            {
                                param.UserIosToken = new List<string>();
                                param.UserIosToken.Add(mp.Token);
                                cpm.PushMessageForIOS(param);
                            }
                        }
                    }
                    #endregion

                }
                else
                {
                    ent.InstanceState = 1;
                    if (upNodeCount < ent.NodeCount)
                    {
                        var nextUsers = CommService.FindNextUsers(ent.ApproalUsers, userId, ent.NodeCount);
                        var to = service.GetDetail(todoId);
                        for (int i = 0; i < nextUsers.Count; i++)
                        {
                            Sys_ToDoList todo = new Sys_ToDoList();
                            todo.ActionURL = to.ActionURL;
                            todo.CreaterName = "系统";
                            todo.CreateTime = DateTime.Now;
                            todo.Name = to.Name;
                            todo.Source = to.Source;
                            todo.State = 0;
                            todo.UpdateTime = DateTime.Now;
                            todo.UrgencyDegree = 0;
                            todo.UserId = nextUsers[i];
                            list.Add(todo);
                        }
                    }
                }
            }
            try
            {
                ent.ApproalUsers = upUsers;
                ent.NodeCount = upNodeCount;
                var mp = ent.InstanceState == 2 ? service.UpdateAll("UCAC" + bid, 1) : service.Update(new Sys_ToDoList() { Id = todoId, State = 1 });
                if (list != null && list.Count > 0)
                    service.SaveToDoList(list);
                Opinions op = new Opinions()
                {
                    Context = opContext,
                    CreateTime = DateTime.Now,
                    Source = "UCAC" + ent.Id,
                    UserId = userId
                };
                oDao.Add(op);
                var bussId = this.dao.Update(ent);
                ReturnModel succ = new ReturnModel() { SourceId = bussId, Message = "操作成功" };
                return succ;
            }
            catch (Exception ex)
            {
                ReturnModel err = new ReturnModel() { SourceId = 0, Message = ex.Message };
                return err;
            }
        }
        /// <summary>
        /// 获取用车申请
        /// </summary>
        /// <param name="orgz">机构ID</param>
        /// <returns></returns>
        public IList<Car_UseCarApplication> GetCarUseList(int userid, int orgz)
        {
            Sys.SysWebservice service = CommService.IntanceSys();
            var pid = Convert.ToInt32(ConfigurationManager.AppSettings["gl"]);
            var users = service.LoadUserByPerAndCanteen(new Sys.Permissions() { Id = pid }, orgz);
            if (users.Users.Count(o => o.Id == userid) > 0)
                return GetCarUseList(orgz);
            return new List<Car_UseCarApplication>();
        }

        public IList<Car_UseCarApplication> GetCarUseList(int orgz)
        {
            IList<Car_UseCarApplication> result = new List<Car_UseCarApplication>();
            var list = this.dao.GetCarUseList(orgz, 3, 0);
            return list.Where(it => it.OldState < 4).ToList();
        }
        /// <summary>
        /// 统计用户用车区域
        /// </summary>
        /// <param name="userId">用户</param>
        /// <returns></returns>
        public IList<Statistics> GetStatistics(int userId)
        {
            return this.dao.GetStatistics(userId);
        }
        /// <summary>
        /// 取消用车
        /// </summary>
        /// <param name="id">用车申请ID</param>
        /// <returns></returns>
        public int CancelUseApplication(int id)
        {
            return this.dao.CancelUseApplication(id);
        }

        /// <summary>
        /// 拒绝派车
        /// </summary>
        /// <param name="id">用车申请ID</param>
        /// <param name="context">意见表</param>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public int RefuseSendCar(int id, string context, int userId)
        {
            Opinions ent = new Opinions() { Source = "UCAC" + id, Context = context, UserId = userId };
            var tag = this.dao.RefuseSendCar(id, ent);
            if (tag > 0)
            {
                var tmp = this.dao.GetDetail(id);
                IList<Sys_ToDoList> list = new List<Sys_ToDoList>();
                Sys_ToDoList todo = new Sys_ToDoList();
                todo.UserId = tmp.UserId;
                todo.ActionURL = string.Empty;
                todo.CreaterName = "系统";
                todo.Source = "UCAC" + id;
                todo.Name = "您的用车申请已拒绝";
                list.Add(todo);
                service.SaveToDoList(list);
            }
            return tag;
        }
        /// <summary>
        /// 保存申诉
        /// </summary>
        /// <param name="ent">保存申诉</param>
        /// <returns></returns>
        public int SaveAppeal(Car_UseCarApplication ent)
        {
            return this.SaveDataForApp(ent);
        }
    }
}
